package com.demo.common.file;

import lombok.SneakyThrows;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 文件操作utils
 */
public class FileUtils {

    /**
     * 文件前缀，处理同名文件的
     */
    public static DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    /**
     * 文本附件
     */
    public static final String TXT="txt";

    /**
     * 图片后缀
     */
    public static Set<String> imageSet= Stream.of("png","gif","jpg").collect(Collectors.toSet());

    /**
     * 公共处理
     * @param response
     * @param fileName
     */
    @SneakyThrows
    public static void setHeaders(HttpServletResponse response, String fileName){
        response.setCharacterEncoding("utf-8");
        int index = fileName.lastIndexOf(".");
        //无后缀当附件，下载
        if(index==-1){
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"utf-8"));
        }
        String suffix=fileName.substring(index+1).toLowerCase();
        //处理ContentType,设置文本及图片，效果是让浏览器知道是预览不是下载
        if(TXT.equals(suffix)){
            response.setContentType("text/plain");
        }else if(imageSet.contains(suffix)){
            response.setContentType("image/"+suffix);
        }else{
            //都不是就下载
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"utf-8"));
        }
    }

    /**
     * 获取文件名称
     * @param oriFileName 原始文件名称
     */
    public static String getNewFileName(String oriFileName){
        String id = formatter.format(LocalDateTime.now());
        //加时间前缀防止重复
        return id+"_"+oriFileName;
    }
}
